<template>
  <div>
    <el-scrollbar :height="height" ref="scrollbarRef">
      <el-row style="justify-content: space-between; margin-bottom: 10px">
        <p class="pinformation">基础信息</p>
        <el-row padding-bottom="5px">
          <el-button @click="save()" type="success" size="small">保存</el-button>
        </el-row>
      </el-row>
      <el-form :model="form" label-width="95" ref="formRef" :rules="rules">
        <el-row>
          <el-col :span="14">
            <el-form-item label="供应商名称：" prop="supplyName">
              <el-input clearable placeholder="请输入供应商名称" v-model="form.supplyName" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="经营性质：" prop="businessNature">
              <el-select v-model="form.businessNature" placeholder="请选择经营性质" clearable style="width: 100%">
                <el-option v-for="dict in sys_business_nature" :key="parseInt(dict.value)" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="通讯地址：" prop="address">
              <el-input clearable placeholder="请输入通讯地址" v-model="form.address" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="联系人：" prop="contacts">
              <el-input clearable placeholder="请输入联系人" v-model="form.contacts" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="联系电话：" prop="telePhone">
              <el-input clearable placeholder="请输入联系电话" v-model="form.telePhone" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="法人姓名：" prop="personName">
              <el-input clearable placeholder="请输入法人姓名" v-model="form.personName" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="纳税人识别号：" label-width="100" prop="taxpayerNumber">
              <el-input clearable placeholder="请输入纳税人识别号" v-model="form.taxpayerNumber" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="营业执照：">
              <fileUpload v-model="form.fileList" :fileType="['jpg', 'gif', 'bmp', 'png', 'pdf']"></fileUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注：" prop="remark">
          <el-input :autosize="{ minRows: 3, maxRows: 7 }" type="textarea" placeholder v-model="form.remark"
            maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>

      <el-row>
        <el-row>
          <p class="pinformation">供应商产品名录</p>
          <p class="totalStyle">共 {{ productList.length }} 条数据</p>
        </el-row>
        <el-row style="padding-bottom: 5px; margin-left: 30px">
          <el-button type="success" link @click="handleDirectory">新增</el-button>
        </el-row>
      </el-row>

      <el-table :data="productList" v-loading="loading" max-height="140px">
        <el-table-column label="供应品类别" align="center" prop="productType" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="产品型号" align="center" prop="productNumber" />
        <el-table-column label="技术指标" align="center" prop="techIndex" />
        <el-table-column label="参考单价" align="center" prop="price" />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button link type="success" @click="editProduct(scope.row)">编辑</el-button>
            <el-button link type="success" @click="deleteProduct(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row>
        <el-row>
          <p class="pinformation">业绩列表</p>
          <p class="totalStyle">共 {{ performanceList.length }} 条数据</p>
        </el-row>
        <el-row style="padding-bottom: 5px; margin-left: 30px">
          <el-button type="success" link @click="handlePerformanceAdd">新增</el-button>
        </el-row>
      </el-row>

      <el-table :data="performanceList" v-loading="loading1" max-height="150px">
        <el-table-column label="业绩名称" align="center" prop="performanceName" width="250" />
        <el-table-column label="业绩文件" align="center" prop="performanceFile">
          <template #default="scope">
            <span @click="proxy.downloadFile(scope.row.fileList, 1)" class="fileNameHover">{{ scope.row.fileList ?
              scope.row.fileList[0].fileName : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button link type="success" @click="editPerformance(scope.row)">编辑</el-button>
            <el-button link type="success" @click="deletePerformance(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row>
        <el-row>
          <p class="pinformation">资质列表</p>
          <p class="totalStyle">共 {{ qualifyList.length }} 条数据</p>
        </el-row>
        <el-row style="padding-bottom: 5px; margin-left: 30px">
          <el-button type="success" link @click="handleQualifyAdd">新增</el-button>
        </el-row>
      </el-row>

      <el-table :data="qualifyList" v-loading="loading2" max-height="150px">
        <el-table-column label="资质名称" align="center" prop="qualifyName" width="250" />
        <el-table-column label="资质文件" align="center">
          <template #default="scope">
            <span @click="proxy.downloadFile(scope.row.fileList, 1)" class="fileNameHover">{{ scope.row.fileList ?
              scope.row.fileList[0].fileName : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="有效期" align="center" prop="yxDate" width="150" />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button link type="success" @click="editQualify(scope.row)">编辑</el-button>
            <el-button link type="success" @click="deleteQualify(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="open" :title="title" width="500px" @close="dialogClose">
      <el-form :model="productForm" ref="directoryRef" :rules="directoryRules" label-width="95">
        <el-form-item label="供应品类别：" prop="productType">
          <el-select v-model="productForm.productType" placeholder="请选择供应品类别" clearable style="width: 100%">
            <el-option v-for="dict in sys_supply_product_type" :key="parseInt(dict.value)" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称：" prop="productName">
          <el-input clearable placeholder="请输入产品名称" v-model="productForm.productName" maxlength="100" />
        </el-form-item>
        <el-form-item label="产品型号：" prop="productNumber">
          <el-input clearable placeholder="请输入产品型号" v-model="productForm.productNumber" maxlength="100" />
        </el-form-item>
        <el-form-item label="技术指标：" prop="techIndex">
          <el-input clearable placeholder="请输入技术指标" v-model="productForm.techIndex" maxlength="100" />
        </el-form-item>
        <el-form-item label="参考价值：" prop="price">
          <el-input clearable placeholder="请输入参考价值" v-model="productForm.price" maxlength="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="directorySave">保存</el-button>
          <el-button type="danger" @click="open = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="open1" :title="title1" width="500px" @close="dialogClose1">
      <el-form :model="performanceForm" ref="performanceRef" :rules="performanceRules" label-width="80">
        <el-form-item label="业绩名称：" prop="performanceName">
          <el-input placeholder v-model="performanceForm.performanceName" />
        </el-form-item>
        <fileUpload v-model="performanceForm.fileList"></fileUpload>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="performanceSave">保存</el-button>
          <el-button type="danger" @click="open1 = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="open2" :title="title2" width="500px" @close="dialogClose2">
      <el-form :model="qualifyForm" ref="qualifyRef" :rules="qualifyRules" label-width="80">
        <el-form-item label="资质名称：" prop="qualifyName">
          <el-input placeholder v-model="qualifyForm.qualifyName" />
        </el-form-item>
        <el-form-item label="有效期：" prop="yxDate">
          <el-date-picker v-model="qualifyForm.yxDate" placeholder="请选择有效期" style="width: 100%" type="date"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <fileUpload v-model="qualifyForm.fileList"></fileUpload>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="qualifySave">保存</el-button>
          <el-button type="danger" @click="open2 = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  saveForm,
  saveDirectory,
  editForm,
  listProduct,
  formProduct,
  delProduct,
  listPerformance,
  delPerformance,
  formPerformance,
  savePerformance,
  listQualify,
  delQualify,
  formQualify,
  saveQualify,
} from "@/api/buy/supplier";
import { nextTick } from "vue";

const { proxy } = getCurrentInstance();

const { sys_business_nature, sys_supply_product_type } = proxy.useDict(
  "sys_business_nature",
  "sys_supply_product_type"
);

const form = ref({ fileList: [] });
const productList = ref([]);

const rules = ref({
  supplyName: [
    { required: true, message: "供应商名称不能为空", trigger: "blur" },
  ],
  businessNature: [
    { required: true, message: "经营性质不能为空", trigger: "blur" },
  ],
  telePhone: [
    {
      pattern: /^\d{11}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  taxpayerNumber: [
    {
      pattern: /^([0-9a-zA-Z])*$/,
      message: "请输入数字或者字母",
      trigger: "blur",
    },
  ],
});

const supplyId = ref("");

const loading = ref(false);
const loading1 = ref(false);
const loading2 = ref(false);

const title = ref("");
const title1 = ref("");
const title2 = ref("");

const open = ref(false);
const open1 = ref(false);
const open2 = ref(false);

const emit = defineEmits(["add"]);

// -------------------------初始化-------------------------
function getList(id) {
  supplyId.value = id;
  loading.value = true;
  loading1.value = true;
  loading2.value = true;
  editForm(supplyId.value).then((res) => {
    form.value = res.data;
  });
  listProduct({ supplyId: supplyId.value }).then((res) => {
    loading.value = false;
    productList.value = res.data;
  });
  listPerformance({ supplyId: supplyId.value }).then((res) => {
    loading1.value = false;
    performanceList.value = res.data;
  });
  listQualify({ supplyId: supplyId.value }).then((res) => {
    loading2.value = false;
    qualifyList.value = res.data;
  });
  proxy.$refs["formRef"].clearValidate();
}

function save(isAuto) {
  return new Promise((resolve, reject) => {
    proxy.$refs["formRef"].validate((valid) => {
      if (valid) {
        saveForm(form.value).then((res) => {
          if (!isAuto) proxy.$modal.msgSuccess("保存成功");
          emit("add", res.data);
          form.value.supplyId = res.data;
          supplyId.value = res.data;
          resolve();
        });
      }
    });
  });
}

// -----------------------------------实录-----------------------------
const productForm = ref({});
const directoryRules = ref({
  productType: [
    { required: true, message: "供应品类别不能为空", trigger: "blur" },
  ],
  productName: [
    { required: true, message: "产品名称不能为空", trigger: "blur" },
  ],
  productNumber: [
    { required: true, message: "产品型号不能为空", trigger: "blur" },
  ],
  techIndex: [{ required: true, message: "技术指标不能为空", trigger: "blur" }],
  price: [{ required: true, message: "参考单价不能为空", trigger: "blur" }],
});

function handleDirectory() {
  save(true).then((res) => {
    open.value = true;
    title.value = "新增供应商产品名录";
    nextTick(() => {
      proxy.$refs["directoryRef"].clearValidate();
    });
  });
}

function directorySave() {
  proxy.$refs["directoryRef"].validate((valid) => {
    if (valid) {
      productForm.value.supplyId = supplyId.value;
      saveDirectory(productForm.value).then((res) => {
        open.value = false;
        title.value = "";
        loading.value = true;
        proxy.$modal.msgSuccess("保存成功");
        listProduct({ supplyId: supplyId.value }).then((res) => {
          loading.value = false;
          productList.value = res.data;
        });
      });
    }
  });
}

function editProduct(row) {
  formProduct(row.productId).then((res) => {
    title.value = "编辑供应商产品名录";
    open.value = true;
    productForm.value = res.data;
    nextTick(() => {
      proxy.$refs["directoryRef"].clearValidate();
    });
  });
}

function deleteProduct(row) {
  proxy.$modal.confirm("确定要删除吗？").then(() => {
    delProduct(row.productId).then((res) => {
      loading.value = true;
      listProduct({ supplyId: supplyId.value }).then((res) => {
        productList.value = res.data;
        loading.value = false;
      });
    });
  });
}

function dialogClose() {
  productForm.value = {};
}

// -------------------------------业绩-----------------------------
const performanceForm = ref({ fileList: [] });
const performanceList = ref([]);
const performanceRules = ref({
  performanceName: [
    { required: true, message: "业绩名称不能为空", trigger: "blur" },
  ],
});

function dialogClose1() {
  performanceForm.value = { fileList: [] };
}

function performanceSave() {
  proxy.$refs["performanceRef"].validate((valid) => {
    if (valid) {
      performanceForm.value.supplyId = supplyId.value;
      savePerformance(performanceForm.value).then((res) => {
        open1.value = false;
        title1.value = "";
        proxy.$modal.msgSuccess("保存成功");
        loading1.value = true;
        listPerformance({ supplyId: supplyId.value }).then((res) => {
          loading1.value = false;
          performanceList.value = res.data;
        });
      });
    }
  });
}

function handlePerformanceAdd() {
  save(true).then((res) => {
    open1.value = true;
    title1.value = "新增业绩";
    nextTick(() => {
      proxy.$refs["performanceRef"].clearValidate();
    });
  });
}

function deletePerformance(row) {
  proxy.$modal.confirm("确定要删除吗？").then(() => {
    delPerformance(row.performanceId).then((res) => {
      loading1.value = true;
      listPerformance({ supplyId: supplyId.value }).then((res) => {
        loading1.value = false;
        performanceList.value = res.data;
      });
    });
  });
}

function editPerformance(row) {
  formPerformance(row.performanceId).then((res) => {
    title1.value = "编辑业绩";
    open1.value = true;
    performanceForm.value = res.data;
    nextTick(() => {
      proxy.$refs["performanceRef"].clearValidate();
    });
  });
}

// -------------------------------资质-----------------------------
const qualifyForm = ref({ fileList: [] });
const qualifyList = ref([]);
const qualifyRules = ref({
  qualifyName: [
    { required: true, message: "资质名称不能为空", trigger: "blur" },
  ],
});
function dialogClose2() {
  qualifyForm.value = { fileList: [] };
}

function qualifySave() {
  proxy.$refs["qualifyRef"].validate((valid) => {
    if (valid) {
      qualifyForm.value.supplyId = supplyId.value;
      saveQualify(qualifyForm.value).then((res) => {
        open2.value = false;
        title2.value = "";
        proxy.$modal.msgSuccess("保存成功");
        loading2.value = true;
        listQualify({ supplyId: supplyId.value }).then((res) => {
          loading2.value = false;
          qualifyList.value = res.data;
        });
      });
    }
  });
}

function handleQualifyAdd() {
  save(true).then((res) => {
    open2.value = true;
    title2.value = "新增资质";
    nextTick(() => {
      proxy.$refs["qualifyRef"].clearValidate();
    });
  });
}

function deleteQualify(row) {
  proxy.$modal.confirm("确定要删除吗？").then(() => {
    delQualify(row.qualifyId).then((res) => {
      loading2.value = true;
      listQualify({ supplyId: supplyId.value }).then((res) => {
        loading2.value = false;
        qualifyList.value = res.data;
      });
    });
  });
}

function editQualify(row) {
  formQualify(row.qualifyId).then((res) => {
    title2.value = "编辑资质";
    open2.value = true;
    qualifyForm.value = res.data;
    nextTick(() => {
      proxy.$refs["qualifyRef"].clearValidate();
    });
  });
}

function resetData() {
  form.value = { fileList: [] };
  qualifyList.value = [];
  performanceList.value = [];
  productList.value = [];
  proxy.$refs["formRef"].clearValidate();
}

defineExpose({
  getList,
  resetData,
});

// 滚动条高度
const height = ref();

function getHeight() {
  nextTick(() => {
    height.value = proxy.getSubFileHeight(proxy, "scrollbarRef");
  });
}

onMounted(() => {
  nextTick(function () {
    getHeight();
    window.addEventListener("resize", getHeight);
  });
})

onUpdated(() => {
  getHeight()
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getHeight);
});
</script>
